package com.epro.dx.activity.messagecenter;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.epro.dx.R;
import com.epro.dx.activity.BaseFragmentActivity;
import com.epro.dx.activity.DetailActivity;
import com.epro.dx.activity.LPLocalBrowserActivity;
import com.epro.dx.activity.SpecialActivity;
import com.epro.dx.activity.StartUpActivity;
import com.epro.dx.adapter.MessageListAdapter;
import com.epro.dx.adapter.MessageListAdapter.MessageClickListener;
import com.epro.dx.adapter.PromotionListAdapter;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshListView;
import com.epro.dx.task.DeleteNoticesAsyncTask;
import com.epro.dx.task.GetActivityListAsyncTask;
import com.epro.dx.task.GetNoticesAsyncTask;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.BannerUtils;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.MessageServiceProvider;
import com.weipu.common.facade.model.MessageModel;
import com.weipu.common.facade.model.ModuleChildrenModel;
import com.weipu.common.facade.model.NoticeGroupsModel;
import com.weipu.common.facade.model.Parmars;
import com.weipu.common.util.AlertToast;

/************************
 * @author Tony
 * @Date:2016-4-7下午1:48:35
 * @描述:消息列表页面
 ************************/
public class MessagesAndPromotionsListActivity extends BaseFragmentActivity implements MessageClickListener {

    public static final String FROMTYPE = "fromWhere";
    public static final int FROMTYPE_HOMEACTIV = 0;
    public static final int FROMTYPE_MESSAGECENTER = 1;
    private Bundle intentBundle;//上个页面跳转传过来的数据
    private PullToRefreshListView messageListView;
    private BaseAdapter messageListAdapter;
    private boolean isPromotion;
    private int fromType;
    private int pageIndex = 0;
    private ArrayList<ModuleChildrenModel> activityList;
    private boolean isLoading = false;
    private ArrayList<MessageModel> messageList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sendScreen();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_messages_list);
        setLeftBtnContent(true, -1);
        getIntentAndInitView();
        initEvent();
        setData();
        excuteTask(false, true);
    }

    /**
     * @创建：Tony 2016-4-14上午10:56:44
     * @描述：初始化事件
     */
    private void initEvent() {
        messageListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                isLoading = true;
                switch (fromType) {
                    case FROMTYPE_HOMEACTIV:
                        //首页跳转活动列表
                        pageIndex = 0;
                        break;
                    case FROMTYPE_MESSAGECENTER:
                        //消息列表
                        pageIndex = 1;
                        break;
                    default:
                        break;
                }
                excuteTask(true, false);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                isLoading = true;
                ++pageIndex;
                excuteTask(false, false);
            }

        });
        //重试🔘的点击事件
        retryBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                excuteTask(false, false);
            }
        });
        //列表点击事件
        messageListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                switch (fromType) {
                    case FROMTYPE_HOMEACTIV:
                        //活动列表的点击事件
                        if (null != activityList && activityList.size() > 0) {
                            BannerUtils.clickActiv(MessagesAndPromotionsListActivity.this, activityList.get(position - 1), Parmars.GETTYPE_HOMEACTIVE, null);
                        }
                        break;

                    default:
                        break;
                }

            }
        });
    }

    /**
     * @创建：Tony 2016-4-13下午5:34:46
     * @描述：访问接口获取数据
     */
    private void excuteTask(final boolean isPullDown, boolean isFirstIn) {
        switch (fromType) {
            case FROMTYPE_HOMEACTIV:
                //加载历史活动数据
                AsyncTaskUtil.executeTask(new GetActivityListAsyncTask(pageIndex, Constant.LIST_PAGE_COUNT, new MyAsyncTaskListenner() {

                    @Override
                    public void onPreTask() {
                        if (!isLoading) {
                            showLoadingLayout(messageListView);
                        }
                    }

                    @Override
                    public void onPostTask(String result, Object obj) {
                        if (!isFinishing()) {
                            hideAllLayout(messageListView);
                            if (isLoading) {
                                isLoading = false;
                                messageListView.onRefreshComplete();
                            }
                            if ("0".equals(result) && null != obj) {
                                @SuppressWarnings("unchecked")
                                ArrayList<ModuleChildrenModel> list = (ArrayList<ModuleChildrenModel>) obj;
                                if (list.size() > 0) {
                                    if (list.size() < 20) {
                                        messageListView.setMode(Mode.PULL_FROM_START);
                                    } else {
                                        messageListView.setMode(Mode.BOTH);
                                    }
                                    if (isPullDown) {
                                        activityList.clear();
                                    }
                                    activityList.addAll(list);
                                    messageListAdapter.notifyDataSetChanged();
                                } else {
                                    if (pageIndex == 0) {
                                        //空数据页面显示
                                        showErrorLayout(messageListView, 0, R.string.promotionlist_nodata_message, R.drawable.promotion_list_nodata_icon);
                                        retryBtn.setVisibility(View.GONE);
                                    }
                                }
                            } else {
                                //错误页面显示
                                if (activityList.size() <= 0) {
                                    //显示错误页面
                                    showErrorLayout(result, messageListView);
                                } else {
                                    //提示错误信息
                                    AlertToast.alert(MessagesAndPromotionsListActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                                    --pageIndex;
                                }
                            }
                        }
                    }
                }));
                break;
            case FROMTYPE_MESSAGECENTER:
                //加载消息列表数据
                if (!isFirstIn) {
                    AsyncTaskUtil.executeTask(new GetNoticesAsyncTask(MessagesAndPromotionsListActivity.this, isPromotion ? MessageModel.NOTICETYPE_EVENT : MessageModel.NOTICETYPE_SYSTEM, pageIndex,
                            Constant.LIST_PAGE_COUNT, new MyAsyncTaskListenner() {

                        @Override
                        public void onPreTask() {
                            if (!isLoading) {
                                showLoadingLayout(messageListView);
                            }
                        }

                        @Override
                        public void onPostTask(String result, Object obj) {
                            if (!isFinishing()) {
                                hideAllLayout(messageListView);
                                if (isLoading) {
                                    isLoading = false;
                                    messageListView.onRefreshComplete();
                                }
                                if ("0".equals(result)) {
                                    ArrayList<MessageModel> messages = (ArrayList<MessageModel>) obj;
                                    if (null != messages && messages.size() > 0) {
                                        if (messages.size() < 20) {
                                            messageListView.setMode(Mode.PULL_FROM_START);
                                        } else {
                                            messageListView.setMode(Mode.BOTH);
                                        }
                                        if (isPullDown) {
                                            messageList.clear();
                                        }
                                        messageList.addAll(messages);
                                        messageListAdapter.notifyDataSetChanged();
                                    } else {
                                        messageListView.setMode(Mode.PULL_FROM_START);
                                        --pageIndex;
                                    }
                                } else {
                                    //提示错误信息
                                    AlertToast.alert(MessagesAndPromotionsListActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                                    --pageIndex;
                                }
                            }

                        }
                    }));
                }
                break;

            default:
                break;
        }
    }

    /**
     * @创建：Tony 2016-4-7下午3:42:50
     * @描述：设置数据显示
     */
    private void setData() {
        switch (fromType) {
            case FROMTYPE_HOMEACTIV:
                //首页跳转活动列表
                pageIndex = 0;
                activityList = new ArrayList<ModuleChildrenModel>();
                messageListAdapter = new PromotionListAdapter(MessagesAndPromotionsListActivity.this, activityList);
                break;
            case FROMTYPE_MESSAGECENTER:
                //消息列表
                pageIndex = 1;
                messageListAdapter = new MessageListAdapter(MessagesAndPromotionsListActivity.this, isPromotion, messageList, this);
                if (messageList.size() < Constant.LIST_PAGE_COUNT) {
                    messageListView.setMode(Mode.PULL_FROM_START);
                } else {
                    messageListView.setMode(Mode.BOTH);
                }
                break;

            default:
                break;
        }
        messageListView.setAdapter(messageListAdapter);
    }

    /**
     * @创建：Tony 2016-4-7下午1:52:03
     * @描述：获取上个页面传过来的数据并初始化页面
     */
    private void getIntentAndInitView() {
        //设置页面标题、初始化视图控件
        Intent intent = getIntent();
        if (null != intent) {
            intentBundle = intent.getBundleExtra(ServerConstant.MessageCenter.INTENT_BUNDLE);
        }
        if (null != intentBundle) {
            isPromotion = intentBundle.getBoolean(ServerConstant.MessageCenter.ISPROMOTION, false);
            fromType = intentBundle.getInt(FROMTYPE);
            int pageTitleId = intentBundle.getInt(ServerConstant.PAGETITLEID, 0);
            setTitleContent(0 != pageTitleId ? getString(pageTitleId) : null);
            messageList = intentBundle.getParcelableArrayList("MessageList");
        }

        messageListView = (PullToRefreshListView) findViewById(R.id.messages_list);
    }

    @Override
    public void onMessageClickListener(View v, int position) {
        // 点击消息列表
        MessageModel messageModel = messageList.get(position);
        if (null != messageModel) {
            goByMessageType(messageModel);
        }
    }

    /**
     * @param messageModel
     * @创建：Tony 2016-5-4下午5:56:46
     * @描述：根据消息跳转类型进行页面跳转
     */
    private void goByMessageType(MessageModel messageModel) {
        Intent intent = new Intent();
        intent.putExtra("NoticeID", messageModel.getNoticeID());
        //增加是否需要校验活动是否过期的标记
        if (messageModel.getNoticeType() == MessageModel.NOTICETYPE_EVENT) {
            intent.putExtra("needCheckValid", true);
        }
        switch (messageModel.getLinkType()) {
            case MessageModel.LINKTYPE_PRODUCTLIST:
                //产品列表
                intent.putExtra(ModuleChildrenModel.ACTIVTYPE, Parmars.GETTYPE_MESSAGE);
                intent.putExtra(ModuleChildrenModel.ACTIVID, messageModel.getNoticeID());
                intent.putExtra("BannerName", messageModel.getTitle());
                intent.setClass(MessagesAndPromotionsListActivity.this, SpecialActivity.class);
                break;
            case MessageModel.LINKTYPE_PRODUCTDETAIL:
                //产品详情
                intent.setClass(MessagesAndPromotionsListActivity.this, DetailActivity.class);
                Bundle data = new Bundle();
                data.putInt(ServerConstant.Parameter.PARAMETER_NAME_PRODUCT_ID,
                        Integer.valueOf(messageModel.getSku()));
                intent.putExtras(data);
                break;
            case MessageModel.LINKTYPE_WAPURL:
                //网页
                intent.setClass(MessagesAndPromotionsListActivity.this, LPLocalBrowserActivity.class);
                intent.putExtra("URL", messageModel.getLinkUrl());
                intent.putExtra("PageTitle", messageModel.getTitle());
                break;
            case MessageModel.LINKTYPE_CONTENTTEXT:
                //不可点击
                intent = null;
                break;

            default:
                break;
        }
        if (null != intent) {
            startActivity(intent);
        }
    }

    @Override
    public void onMessageLongClickListener(View v, final int position) {
        //长按消息列表删除对应消息
        MessageModel messageModel = messageList.get(position);
        showDeleteMessageDialog(messageModel, position);
    }

    /**
     * @创建：Tony 2016-5-5上午9:37:05
     * @描述：弹窗确认删除消息
     * @param messageModel
     */
    private AlertDialog deleteMessageDialog;

    private void showDeleteMessageDialog(final MessageModel messageModel, final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MessagesAndPromotionsListActivity.this);
        builder.setTitle(R.string.delete)
                .setMessage(R.string.user_wish_confirm_del);
        builder.setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //取消
                deleteMessageDialog.dismiss();
            }
        });
        builder.setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                deleteMessageDialog.dismiss();
                //确认删除
                if (null != messageModel) {
                    ArrayList<String> notices = new ArrayList<String>();
                    notices.add(messageModel.getNoticeID());
                    AsyncTaskUtil.executeTask(new DeleteNoticesAsyncTask(MessagesAndPromotionsListActivity.this, MessageServiceProvider.ACTIONTYPE_NOTICEIDS, notices, new MyAsyncTaskListenner() {

                        @Override
                        public void onPreTask() {
                            showWaitingDialog();
                        }

                        @Override
                        public void onPostTask(String result, Object obj) {
                            if (!isFinishing()) {
                                hideWaitingDialog();
                                if ("0".equals(result)) {
                                    //删除成功，将内存数据删除
                                    messageList.remove(position);
                                    messageListAdapter.notifyDataSetChanged();
                                } else {
                                    AlertToast.alert(MessagesAndPromotionsListActivity.this, ServerConstant.ReturnCode.MESSAGEMAP.get(result));
                                }
                            }
                        }
                    }));
                }
            }
        });
        deleteMessageDialog = builder.create();
        deleteMessageDialog.show();
    }
}
